package com.bbkb.quartz.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.util.StrUtil;
import com.bbkb.common.constants.CommonConstant;
import com.bbkb.common.constants.ShiroConstant;
import com.bbkb.common.vo.Result;
import com.bbkb.quartz.util.TreeUtil;
import com.bbkb.user.dto.SysMenuDTO;
import com.bbkb.user.dto.SysUserDTO;
import com.bbkb.user.remoting.ISysMenuRemoting;
import com.bbkb.user.remoting.ISysUserRemoting;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @功能 登录
 * @作者 沈飞超
 * @日期 2020年09月27日 6:08
 */
@Controller
@Slf4j
public class LoginController {

    //创造图形验证码对象并定义图形验证码的长和宽
    private final ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(65, 23, 4, 0);

    @Autowired
    private ISysUserRemoting sysUserRemoting;
    @Autowired
    private ISysMenuRemoting sysMenuRemoting;

    @RequestMapping("/captcha")
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ServletOutputStream out = response.getOutputStream();
        // 自定义纯数字的验证码（随机4位数字，可重复）
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        captcha.setGenerator(randomGenerator);
        //生成验证码
        captcha.createCode();
        captcha.write(out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

    @RequestMapping("/")
    public String index() {
        return "admin/login";
    }

    @RequestMapping("/adminLogin")
    public String adminLogin() {
        return "admin/login";
    }

    @RequestMapping("/adminToLogin")
    @ResponseBody
    public Result toLogin(
            String username,
            String password,
            String verifyCode,
            String rememberMe) {
        try {
//            if (!verifyCode.equals(captcha.getCode())) {
//                return Result.error("验证码错误！");
//            }
            if (StrUtil.isBlank(username)) {
                return Result.error("用户名不可为空");
            }
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                token.setRememberMe("on".equals(rememberMe));
                subject.login(token);//验证权限(用户名与密码是否一致) AuthRealm->doGetAuthenticationInfo
                SysUserDTO sysUser = sysUserRemoting.getByUserName(username);
                subject.getSession().setAttribute(ShiroConstant.SESSION_USER, sysUser);
                return Result.success(sysUser);
            } else {
                return Result.success(subject.getSession().getAttribute(ShiroConstant.SESSION_USER));
            }
        } catch (UnknownAccountException | LockedAccountException e) {
            return Result.error(e.getMessage());
        } catch (AuthenticationException e) {
            return Result.error("用户名或密码错误！");
        } catch (Exception e) {
            log.error("登陆失败", e);
            return Result.error("用户名或密码错误！");
        }
    }

    @RequestMapping("/admin/main")
    public ModelAndView main() {
        SysUserDTO sysUser = (SysUserDTO) SecurityUtils.getSubject().getSession().getAttribute(ShiroConstant.SESSION_USER);
//        List<SysMenu> sysMenuList;
//        if (SuperAdminEnum.YES.getKey().equals(sysUser.getSuperAdmin())) {
//            sysMenuList = sysMenuService.getAllSysMenus();
//        } else {
//            sysMenuList = sysMenuService.getSysMenusByUserId(sysUser.getId());
//        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", sysUser);
//        TreeUtil util = new TreeUtil(sysMenuList);
//        modelAndView.addObject("menuList", util.getRootNodes());
        modelAndView.setViewName("admin/main");
        return modelAndView;
    }

    @RequestMapping("/admin/getMenu")
    @ResponseBody
    public List<TreeUtil.TreeNode> getMenu() {
        SysUserDTO sysUser = (SysUserDTO) SecurityUtils.getSubject().getSession().getAttribute(ShiroConstant.SESSION_USER);
        List<SysMenuDTO> sysMenuList;
        if (CommonConstant.YES == sysUser.getSuperAdmin()) {
            sysMenuList = sysMenuRemoting.getAllSysMenus();
        } else {
            sysMenuList = sysMenuRemoting.getSysMenusByUserId(sysUser.getId());
        }
        TreeUtil util = new TreeUtil(sysMenuList);
        return util.getRootNodes();
    }

    @RequestMapping("/adminLogout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/adminLogin";
    }
}
